package com.ruoyi.tt.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.tt.domain.TtUser;
import com.ruoyi.tt.mapper.TtUserMapper;
import com.ruoyi.tt.service.LoginService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @date 2022/10/16 10:00
 **/
@Service
public class LoginServiceImpl implements LoginService {
    @Value("${token.secret}")
    private String secret;
    @Value("${token.expireTime}")
    private int expireTime;

//    @Autowired
//    private TokenService tokenService;

    @Autowired
    private TtUserMapper ttUserMapper;
    @Autowired
    private RedisCache redisCache;
    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
//    public void refreshToken(LoginUser loginUser) {
//        loginUser.setLoginTime(System.currentTimeMillis());
//        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
//        // 根据uuid将loginUser缓存
//        String userKey = getTokenKey(loginUser.getToken());
//        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
//    }

    /**
     * 登录方法
     *
     * @param user
     * @return
     */
    @Override
    public String login(TtUser user) {
        String avatar = user.getAvatar();
        // 根据头像地址来查询用户，唯一标识
        TtUser ttUser = ttUserMapper.selectTtUserByavatar(avatar);
        if (ttUser == null) {
            ttUserMapper.insertTtUser(user); // 就注册
        }
        // 就直接进行登录生成token
        String token = IdUtils.fastUUID();
        // 刷新token 生成的token，又存放到redis中 login:tokens:xxxx
        LoginUser loginUser = new LoginUser();
        loginUser.setToken(token);
//        refreshToken(loginUser);
        Map<String, Object> claims = new HashMap<>();
        // 用户id
        claims.put("id", user.getId());
        claims.put(Constants.LOGIN_USER_KEY, token);
        // 根据生成的token又生成jwt
        token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

}
